/*
 * Copyright (C) 2015 yixun All Rights Reserved.
 * 
 * AreaServiceImpl.java
 */
package com.yixun.qfbao.api.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.yixun.common.page.Page;
import com.yixun.qfbao.api.service.M2Servcie;
import com.yixun.qfbao.apidto.GetM2ProjectsReqDto;
import com.yixun.qfbao.apidto.GetM2ProjectsResDto;
import com.yixun.qfbao.config.M2ApiConfig;
import com.yixun.qfbao.model.Company;
import com.yixun.qfbao.model.enums.M2RequestEnum;
import com.yixun.qfbao.service.CompanyService;
import com.yixun.qfbao.util.EncryptUtil;
import com.yixun.qfbao.util.RequestUtil;
import com.yixun.qfbao.xf.model.Premises;
import com.yixun.qfbao.xf.model.dto.M2ProjectDto;
import com.yixun.qfbao.xf.model.dto.PremisesDto;
import com.yixun.qfbao.xf.service.PremisesService;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * [文件名称]<br>
 * CustomerPremisesServiceImpl.java<br>
 * <br>
 * [文件描述]<br>
 * 报备相关<br>
 * <br>
 *
 * @author JHSong
 * @version 1.00
 */
@Service
public class M2ServiceImpl implements M2Servcie {

	private Logger logger = LoggerFactory.getLogger(M2ServiceImpl.class);

	@Autowired
	private CompanyService companyService;
	@Autowired
	private PremisesService premisesService;
	@Autowired
	private M2ApiConfig m2ApiConfig;

	@Override
	public GetM2ProjectsResDto getM2Projects(GetM2ProjectsReqDto reqDto) {
		GetM2ProjectsResDto resDto = new GetM2ProjectsResDto();
		Page<M2ProjectDto> resPage = new Page<M2ProjectDto>();
		Company company = companyService.selectById(reqDto.getHigherId());
		//M2的商户号
		String merchantCode = company.getMerchantCode();
		Map<String, String> map = new HashMap<String, String>();
		map.put("projectName", reqDto.getProjectName());
		map.put("merchantCode", "me10001");
		map.put("token", "me10001");
		map.put("version", null);
		map.put("pageNumber", String.valueOf(reqDto.getPageNumber()));
		map.put("pageSize", String.valueOf(reqDto.getPageSize()));
		String signStr = EncryptUtil.createLinkString(map);
		String sign = EncryptUtil.Encrypt(signStr, "MD5");
		map.put("sign", sign);
		//组装Params参数
		Map<String, Object> paramsMap = new HashMap<String, Object>();
		paramsMap.put("params", map);
		com.alibaba.fastjson.JSONObject json = new com.alibaba.fastjson.JSONObject(paramsMap);
		String jsonStr = json.toString();
		//组装参数body
		Map<String, String> body = new HashMap<String, String>();
		body.put("body", jsonStr);
		String resStr = null;
		try {
			String url = m2ApiConfig.getM2RequestUrl() + M2RequestEnum.QUERY_PROJECT.getNo();
			resStr = RequestUtil.buildRequest(url, body, "UTF-8");
			com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(resStr);
			String resDataStr = jsonObject.getString("resData");
			com.alibaba.fastjson.JSONObject resDataJson = com.alibaba.fastjson.JSONObject.parseObject(resDataStr);
			String result = resDataJson.getString("result");
			String projectStr = resDataJson.getString("resPage");
			if("1".equals(result) && StringUtils.isNotBlank(projectStr)){
				JSONObject resJsonObject = JSONObject.parseObject(projectStr);
				if(StringUtils.isNotBlank(resJsonObject.getString("pageNumber"))){
					resPage.setPageNumber(resJsonObject.getInteger("pageNumber"));
				}
				if(StringUtils.isNotBlank(resJsonObject.getString("pageSize"))){
					resPage.setPageSize(resJsonObject.getInteger("pageSize"));
				}
				if(StringUtils.isNotBlank(resJsonObject.getString("total"))){
					resPage.setTotal(resJsonObject.getInteger("total"));
				}
				if(StringUtils.isNotBlank(resJsonObject.getString("totalPages"))){
					resPage.setTotalPages(resJsonObject.getInteger("totalPages"));
				}

				List<M2ProjectDto> m2List = JSONObject.parseArray(resJsonObject.getString("rows"), M2ProjectDto.class);
				if(m2List.size() > 0){
					//获取商户下已同步的M2楼盘
                    List<String> projectCodeList = m2List.stream().map(M2ProjectDto::getProjectCode).collect(Collectors.toList());
					PremisesDto premisesDto = new PremisesDto();
					premisesDto.setCompanyId(company.getId());
					premisesDto.setProjectCodeM2List(projectCodeList);
					List<Premises> premisesList = premisesService.selectIdListByDto(premisesDto);

					//判断是否通不过改楼盘
					for(int ii=0; ii<m2List.size(); ii++){
						M2ProjectDto m2ProjectDto = m2List.get(ii);
						String projectCode = m2ProjectDto.getProjectCode();

						if(null != premisesList && premisesList.size() > 0){
							for(Premises premises: premisesList){
								String projectCodeM2 = premises.getProjectCodeM2();
								if(projectCode.equals(projectCodeM2)){
									m2ProjectDto.setPremisesName(premises.getName());
								}
							}
						}
					}
					resPage.setRows(m2List);
				}
			}
			resDto.setData(resPage);
		} catch (HttpException e) {
			logger.error("M2ServiceImpl ==> getM2Projects HttpException: {}", e);
		} catch (UnsupportedEncodingException e) {
			logger.error("M2ServiceImpl ==> getM2Projects UnsupportedEncodingException: {}", e);
		} catch (GeneralSecurityException e) {
			logger.error("M2ServiceImpl ==> getM2Projects GeneralSecurityException: {}", e);
		} catch (Exception e){
			logger.error("M2ServiceImpl ==> getM2Projects error: {}", e);
		}
		return resDto;
	}
}
